/**
 * Created by oneminute on 7/17/14.
 */

var lz = require("../lib/utils/modules")();

exports.post = function (_req, _res, _opts, _callback) {
    var user = _req.user;
    if (!user) {
        lz.Logger.warn("/releasegoods: 用户为临时用户，不能发布商品");
        _callback(lz.Config.errors.getError(lz.Config.errors.REQUEST_TEMPUSER_ERROR));
        return;
    }
    var photos = [];
    for (var i = 1; i <= 4; i++) {
        if (_req.files["photo" + i] && _req.files["photo" + i].size > 0) {
            photos.push(_req.files["photo" + i].path);
            lz.Logger.debug("path: ", _req.files["photo" + i].path);
        }
    }
    var description = _req.body.description;
    var price = _req.body.price;

    lz.ImageManager.handleGoodsPhotos(photos, function (err, _photonames) {
        lz.Logger.debug('/releasegoods: 生成的图片列表为: ', _photonames);
        var commodity = new lz.Commodity({
            id: lz.Utils.getUUID("c_"),
            uid: user.id,
            description: description,
            price: price,
            photos: _photonames
        });
        commodity.save(function (_err, _commodity) {
            lz.Logger.debug("更新用户对象的上架商品列表: ", _commodity);
            user.commodities.unshift(commodity);
            user.inbusiness = true;
            user.save({saveAll: false}, function (_err, _user) {
                lz.Logger.debug("/releasegoods: 发布商品完成。");
                if (_err) {
                    _callback(_err);
                } else {
                    _callback(null, user);
                }
            });
        });
    });
};
